package br.facet.dao;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.facet.pojo.Cliente;
import br.facet.pojo.Pedido;
import br.facet.pojo.Venda;
import br.facet.utils.HibernateUtils;

public class VendaDAO {

	public void salvarVenda(Pedido itens, Cliente cliente){
		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			sessao.save(itens);
			sessao.save(cliente);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if(sessao != null){
				try {
					sessao.close();					
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	}
	
	public void salvar(Venda venda){
		Session sessao = null;
		Transaction tx = null;

		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			sessao.saveOrUpdate(venda);
			tx.commit();

		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}
	
	@SuppressWarnings("unchecked")
	public List<Venda> listByDate(Date date) {
		String hql = "select v from Venda v where v.dtVenda = :date";
		Session sessao = null;
		Transaction tx = null;
		List<Venda> result = null;
		try {
			sessao = HibernateUtils.getSession();
			tx = sessao.beginTransaction();
			result = sessao.createQuery(hql).setParameter("date", date).list();
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			result = Collections.<Venda>emptyList();
		} finally {
			if (sessao != null) {
				try {
					sessao.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}
	
		return result;
	}
}
